<?php
//No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class OwnserviceModelUser extends JModel
{
	/**
	 * User data
	 *
	 * @var object
	 */
	var $_data = null;

	/**
	 * Constructor
	 *
	 * @since 1.0
	 */
	function __construct()
	{
		parent::__construct();

		$id = JRequest::getVar('id', 0, '', 'int');
		$this->setId((int)$id);
	}

	/**
	 * Method to set the identifier
	 *
	 * @access	public
	 * @param	int user identifier
	 */
	function setId($id){
		// Set user id and wipe data
		$this->_id	    = $id;
		$this->_data	= null;
	}

	/**
	 * Overridden get method to get properties from the user
	 *
	 * @access	public
	 * @param	string	$property	The name of the property
	 * @param	mixed	$value		The value of the property to set
	 * @return 	mixed 				The value of the property
	 * @since	1.0
	 */
	function get($property, $default=null)
	{
		if ($this->_loadData()) {
			if(isset($this->_data->$property)) {
				return $this->_data->$property;
			}
		}
		return $default;
	}

	/**
	 * Method to get row data
	 *
	 * @access	public
	 * @return	array
	 * @since	1.0
	 */
	function &getData(){
		if ($this->_loadData()){

		} else $this->_initData();

		return $this->_data;
	}

	/**
	 * Method to load user data
	 *
	 * @access	private
	 * @return	boolean	True on success
	 * @since	1.0
	*/
	function _loadData() {

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get var
		$gid		= $user->gid;
		$level		= $ownuser->get('level_id');

		$where = ' AND 	group_id <> 1';

		if( $gid < 25 && $level < 6 ) {
			$where .=' AND branch_id = '.$ownuser->get('branch_id');
		}

		// Lets load the user if it doesn't already exist
		if (empty($this->_data)) {

			$query = ' SELECT p.*, u.username, u.email, u.name, u.gid, g.name AS groupname,b.name AS branchname '
					.' FROM #__ownservice_users AS p '
					.' LEFT JOIN #__users AS u ON u.id=p.user_id '
					.' LEFT JOIN #__ownservice_branches AS b ON b.id = p.branch_id '
					.' LEFT JOIN #__ownservice_groups AS g ON g.id=p.group_id '
					.' WHERE p.id = '.$this->_id
					.$where
					;
			$this->_db->setQuery($query);
			$this->_data = $this->_db->loadObject();

			return (boolean) $this->_data;
		}

		return true;
	}


	/**
	 * Method to initialise the user data
	 *
	 * @access	private
	 * @return	boolean	True on success
	 * @since	1.0
	 */
	function _initData() {

		// Lets load the user if it doesn't already exist
		if (empty($this->_data)){

			$user = new stdClass();
			$user->id		 = 0;
			$user->gid		 = 18;
			$user->group_id	 = 0;
			$user->branch_id = null;
			$user->secret	 = null;
			$user->firstname = null;
			$user->lastname  = null;
			$user->username  = null;
			$user->nickname  = null;
			$user->birthday  = null;
			$user->id_type	 = null;
			$user->id_number = null;
			$user->issuer	 = null;
			$user->phone_no  = null;
			$user->address	 = null;
			$user->city		 = null;
			$user->state	 = null;
			$user->postcode	 = null;
			$user->country	 = 'Australia';
			$user->address   = null;
			$user->email	 = null;

			$this->_data	 = $user;
			return (boolean) $this->_data;
		}
		return true;
	}

	/**
	 * Method to store data to user
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.0
	 */

	function store($data){

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get var
		$level = $ownuser->get('level_id');

		$row = & $this->getTable( 'ownservice_user' , '');

		if(!isset($data['branch_id']) && $level < 6) {
			$data['branch_id'] = $ownuser->get('branch_id');
		}	
	
		// bind it to the table
		if (!$row->bind($data)) {
			$this->setError( $this->_db->getErrorMsg() );
			return false;
		}

		// Are we saving from an user edit?
		if ($row->id) {
			$datenow =& JFactory::getDate();
			$row->modified 		= $datenow->toMySQL();
			$row->modified_by 	= $user->get('id');
		}

		$row->created_by 	= $row->created_by ? $row->created_by : $user->get('id');

		if ($row->created && strlen(trim( $row->created )) <= 10) {
			$row->created 	.= ' 00:00:00';
		}

		$config =& JFactory::getConfig();
		$tzoffset = $config->getValue('config.offset');
		$date =& JFactory::getDate($row->created, $tzoffset);
		$row->created = $date->toMySQL();

		// Make sure the data is valid
		if (!$row->check()) {
			$this->setError($row->getError() );
			return false;
		}

		// Store it in the db
		if (!$row->store()) {
			$this->setError( $this->_db->getErrorMsg() );
			return false;
		}

		$this->_data =& $row;

		return true;
	}

	/**
	 * Method to get countries
	 *
	 * @access public
	 * @return object
	*/
	function getCountries(){

		$query = ' SELECT * FROM #__ownservice_countries ORDER BY country';

		$this->_db->setQuery($query);
		$countries = $this->_db->loadObjectList();

		return $countries;
	}

	/**
	 * Method to get groups
	 * 
	 * @return array
	 * @since 1.5
	*/
	function getGroups () {

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get var
		$level = $ownuser->get('level_id');

		$where = '';
		
		if($level == 4) {
			$where = ' AND id=2 ';
		} else if($level == 5) {
			$where = ' AND ( id=2 OR id=3 or id=4 )';
		}

		$query = 'SELECT id, name'
				. ' FROM #__ownservice_groups '
				.' WHERE name <> '.$this->_db->Quote('Member')
				.$where
				. ' ORDER BY id ASC'
				;
		$this->_db->setQuery($query);
		$groups = $this->_db->loadObjectList();

		return $groups;	
	}

	/**
	 * Method to get branches
	 *
	 * @return array
	 * @since 1.5
	*/
	function getBranches(){
		$query = 'SELECT id, name'
				. ' FROM #__ownservice_branches '
				.' WHERE published = 1 AND deleted=0'
				. ' ORDER BY name ASC'
				;
		$this->_db->setQuery($query);
		$branches = $this->_db->loadObjectList();
		return $branches;
	}

	/**
	 * Method get user
	 *
	 * @return object
	 * @since 1.5
	*/
	function getUser($id) {

		$query = ' SELECT p.*, u.name FROM #__ownservice_users AS p '
				.' LEFT JOIN #__users AS u ON u.id=p.user_id '
				.' WHERE u.id='.$id.' AND u.block = 0 ';
		$this->_db->setQuery($query);
		$profile = $this->_db->loadObject();

		return $profile;
	}

	/**
	  * Method to check user already exists
	  *
	  * @return boolean True or False
	  * @since 1.0
	 */
	 function checkMember($id)
	{
		$query	= ' SELECT * FROM #__ownservice_users'
					  .' WHERE id_number='.$this->_db->Quote($id);

		$this->_db->setQuery($query);
		//echo $this->_db->_sql;
		$row	= $this->_db->loadObject();

		return (boolean) $row;
	 }

	 /**
	  * Method to check username already exists
	  *
	  * @return boolean True or False
	  * @since 1.0
	 */
	 function checkUsername($username)
	{
		$query = ' SELECT * FROM #__users'
					.' WHERE username ='.$this->_db->Quote($username);

		$this->_db->setQuery($query);
		//echo $this->_db->_sql;
		$row	= $this->_db->loadObject();

		return (boolean) $row;
	 }

	/**
	 * Method get currencies
	 *
	 * @return objectlist
	 * @since 1.5
	*/
	function getCurrencies() {

		$query = ' SELECT * FROM #__ownservice_exchangerates WHERE deleted=0';
		$this->_db->setQuery($query);
		$currencies = $this->_db->loadObjectList();

		return $currencies;
	}

	/**
	 * Method get Files
	 *
	 * @return objectlist
	 * @since 1.5
	*/
	function getFiles($userid) {

		$query = ' SELECT * FROM #__ownservice_files  WHERE userid='.$userid;

		$this->_db->setQuery($query);
		$files = $this->_db->loadObjectList();

		if($files) {
			$path = OwnserviceHelper::getParams('path', 'images/stories/ownservices');
			foreach($files as $file) {
				if(OwnserviceHelper::isImage($file->filename)) {
					$info = @getimagesize(JPATH_SITE.DS.$path.DS.$file->userid.DS.$file->filename);
					if (($info[0] > 150) || ($info[1] > 150)) {
						$dimensions		= OwnserviceHelper::imageResize($info[0], $info[1], 150);
						$file->width	= $dimensions[0];
						$file->height	= $dimensions[1];
					} else {
						$file->width	= $info[0];
						$file->width	= $info[1];
					}
				}
			}
		}

		return $files;
	}
}